import React from 'react';
import { Button, Form, Input, InputNumber, message, Table, Modal, Pagination } from 'antd';
import { connect } from 'dva';
import RelatedKnowledge from '@/utils/RelatedKnowledge';
import KnowledgeReadOnly from '@/pages/KnowledgeManagement/Overview/EditingKnowledge/knowledgeReadOnly';
import qa from '@/pages/KnowledgeManagement/Overview/editQa/qa';

const { confirm } = Modal;

class QuestionList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      total: 0,
      loading: false,
      current: 1,
      size: 10,
      currentLabel: null,
      relatedVisible: false,
      relatedData: [],
      hotType:0
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  /**
   * 删除标签后更新列表
   */
  refreshQuestionList = () => {
    this.setState({
      list: [],
      total: 0,
      loading: false,
      current: 1,
      size: 10,
      currentLabel: null,
    });
  };

  /**
   * 选中标签后展示对应的问题列表和相关信息
   */
  getQuestionsBuCurrentLabel = info => {
    this.setState(
      {
        currentLabel: info,
      },
      () => {
        if (info.type === 0) {
          this.props.form.setFieldsValue({
            pcNum: info.pcCount,
            mobileNum: info.mobileCount,
          });
        }
        this.getQuestionList();
      }
    );
  };

  /**
   * 获取标签知识点列表
   */
  getQuestionList = () => {
    const { dispatch } = this.props;
    const { current, size, currentLabel } = this.state;
    this.setState(
      {
        loading: true,
      },
      () => {
        dispatch({
          type: 'hotQuestion/getHotQuestionList',
          payload: { current, size, hotLabelId: currentLabel.id },
          callback: res => {
            this.setState({
              list: res.records,
              total: res.total,
              loading: false,
            });
            this.RelatedKnowledge.setRelatedListFromHot(res.records);
          },
        });
      }
    );
  };

  /**
   *
   * 保存推荐数
   */
  saveLabelCount = () => {
    const { currentLabel } = this.state;
    const { dispatch, robotId } = this.props;
    this.props.form.validateFields((errors, values) => {
      if (!errors) {
        dispatch({
          type: 'hotQuestion/doEditLabel',
          payload: {
            id: currentLabel.id,
            name: currentLabel.name,
            pcCount: values.pcNum,
            mobileCount: values.mobileNum,
            imgUrl: currentLabel.imgUrl,
            imgName: currentLabel.imgName,
            robotId,
          },
          callback: res => {
            message.info(res.message);
          },
        });
      }
    });
  };

  /**
   * 关联知识点-打开弹窗
   */
  openRelatedKnowledgeModal = (type) => {
    if(type === 1){
      this.RelatedKnowledge.setRelatedListFromHot([]);
    }
    this.setState({
      relatedVisible: true,
      hotType:type
    },() => {
      this.RelatedKnowledge.getList()
    });
  };

  /**
   * 关联知识点-关闭弹窗
   */
  closeRelatedModal = () => {
    this.RelatedKnowledge.resetLabel();
    this.setState({
      relatedVisible: false,
    });
  };

  /**
   * 关联知识点
   */
  getRelatedListToRelated = data => {
    const { currentLabel,hotType } = this.state;
    const qaId = data[data.length - 1].id;
    if(hotType === 0){
      this.doRelated(qaId);
    }

  };

  /**
   * 关联知识点确定的回调
   */
  selectOk = (rowList,tagName) => {
    if(rowList.length > 0){
      const qaId = rowList[rowList.length - 1].id;
      this.doRelated(qaId,tagName);
    }
  }

  /**
   * 关联知识点调用接口
   */
  doRelated = (qaId,tagName) => {
    const { currentLabel } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'hotQuestion/doRelatedData',
      payload: { qaId, hotLabelId: currentLabel.id,tagName },
      callback: res => {
        message.info(res.message);
        this.RelatedKnowledge.getList();
        this.getQuestionList();
        this.setState({
          relatedData: data,
        });
      },
    });
  }

  /**
   * 排序input修改
   */
  changeOrder = (value, index) => {
    let { list } = this.state;
    list[index].labelQaOrder = value;
    this.setState({
      list,
    });
  };

  /**
   * 保存排序
   */
  saveOrder = row => {
    const { dispatch } = this.props;
    dispatch({
      type: 'hotQuestion/doSaveOrder',
      payload: { id: row.id, order: row.labelQaOrder },
      callback: res => {
        message.info(res.message);
        this.getQuestionList();
      },
    });
  };

  /**
   * 删除
   */
  removeQuestion = id => {
    const that = this;
    confirm({
      title: '是否确定删除该问题',
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk() {
        const { dispatch } = that.props;
        dispatch({
          type: 'hotQuestion/doRemoveQuestion',
          payload: { id },
          callback: res => {
            message.info(res.message);
            that.getQuestionList();
          },
        });
      },
      onCancel() {},
    });
  };

  /**
   * 查看
   */
  toView = row => {
    const qaId = row.qaId;
    row.id = qaId;
    this.EditingKnowledge.showEditDrawer(row, null, null, 'hot');
  };

  /**
   * 分页
   * @returns {*}
   */
  changePage = (page,size) => {
    this.setState({
      current:page,
      size
    },() => {
      this.getQuestionList()
    })
  }

  render() {
    const { list, total, loading, current, currentLabel, relatedVisible,hotType } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { robotId } = this.props;
    const columns = [
      {
        title: '序号',
        dataIndex: 'serialNum',
        width: 100,
        render: (text, row, index) => {
          return index + 1;
        },
      },
      {
        title: '标准问题',
        dataIndex: 'question',
        key: 'question',
        width: 300,
      },
      {
        title: '问答频次',
        dataIndex: 'counts',
        key: 'counts',
        width: 200,
      },
      {
        title: '排序',
        dataIndex: 'labelQaOrder',
        key: 'labelQaOrder',
        width: 200,
        render: (text, row, index) => {
          return (
            <InputNumber value={text} min={0} onChange={value => this.changeOrder(value, index)} />
          );
        },
      },
      {
        title: '操作',
        width: 200,
        render: (text, row, index) => {
          return (
            <div>
              <Button type={'primary'} size={'small'} onClick={() => this.saveOrder(row)} style={{marginRight:10}}>
                保存
              </Button>
              <Button type={'danger'} size={'small'} onClick={() => this.removeQuestion(row.id)}>
                删除
              </Button>
            </div>
          );
        },
      },
    ];
    const columns1 = [
      {
        title: '标签名',
        dataIndex: 'tagName',
        width: 100,
      },
      {
        title: '标准问',
        dataIndex: 'question',
        key: 'question',
        width: 300,
      },
      {
        title: '操作',
        width: 200,
        render: (text, row, index) => {
          return (
            <div>
              <Button type={'danger'} size={'small'} onClick={() => this.removeQuestion(row.id)}>
                删除
              </Button>
            </div>
          );
        },
      },
    ];

    return (
      <div>
        {currentLabel && currentLabel.type === 1 ? (
          <div>
            <h3>
              {currentLabel ? currentLabel.name : '标签'}
              <Button type={'primary'} style={{marginLeft:10}} onClick={() => this.openRelatedKnowledgeModal(1)}>新增</Button>
            </h3>
          </div>
        ) : (
          <div style={{ overflow: 'hidden' }}>
            <h3 style={{ width: '50%', float: 'left' }}>
              {currentLabel ? currentLabel.name : '标签'}
            </h3>
            <div style={{ width: '50%', textAlign: 'right', float: 'left' }}>
              <Button
                type={'primary'}
                onClick={() => this.openRelatedKnowledgeModal(0)}
                disabled={!currentLabel}
              >
                关联知识点
              </Button>
            </div>
          </div>
        )}
        {
          currentLabel && currentLabel.type === 1 ? '' :
            <div style={{ margin: '10px 0px' }}>
              <Form layout={'inline'}>
                <Form.Item label={'PC端推荐数'}>
                  {getFieldDecorator('pcNum', {
                    rules: [{ required: true, message: '请输入PC端推荐数' }],
                  })(<InputNumber min={0} />)}
                </Form.Item>
                <Form.Item label={'移动端推荐数'}>
                  {getFieldDecorator('mobileNum', {
                    rules: [{ required: true, message: '请输入移动端推荐数' }],
                  })(<InputNumber min={0} />)}
                </Form.Item>
                <Form.Item>
                  <Button type={'primary'} disabled={!currentLabel} onClick={this.saveLabelCount}>
                    保存
                  </Button>
                </Form.Item>
              </Form>
            </div>
        }

        <div>
          <Table
            rowKey={'id'}
            columns={currentLabel && currentLabel.type === 1 ? columns1 : columns}
            dataSource={list}
            loading={loading}
            pagination={false}
            scroll={{ x: 1300, y: 470 }}
          />
          {total > 10 ? (
            <Pagination
              style={{ textAlign: 'right', marginTop: 16 }}
              total={total}
              current={current}
              onChange={this.changePage}
              // showSizeChanger={true}
              showQuickJumper={true}
              // onShowSizeChange={this.changePage}
            />
          ) : null}
        </div>
        <RelatedKnowledge
          visible={relatedVisible}
          onClose={this.closeRelatedModal}
          getRelatedList={this.getRelatedListToRelated}
          onRef={ref => (this.RelatedKnowledge = ref)}
          qaId={null}
          type={'hotQuestion'}
          hotType={hotType}
          selectAction={this.selectOk}
          robotId={robotId}
          hotLabelId={currentLabel ? currentLabel.id : null}
        />
        <KnowledgeReadOnly
          onRef={ref => (this.EditingKnowledge = ref)}
          refreshList={this.refreshList}
          categoryId={null}
          authority={''}
        />
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(QuestionList));
